<template>
  <v-navigation-drawer v-model="dictDetailVisible" location="right" width="45%" temporary class="dict-detail-drawer">
    <v-card class="h-100 d-flex flex-column">
      <v-card-title class="d-flex align-center">
        <span>字典类型 - </span>
        <v-chip color="info" size="small" class="ml-2">{{ title }}</v-chip>
        <v-spacer></v-spacer>
        <v-btn icon @click="close">
          <v-icon>mdi-close</v-icon>
        </v-btn>
      </v-card-title>

      <v-card-text class="flex-grow-1">
        <!-- 查询表单 -->
        <v-row class="mb-4">
          <v-col cols="12" md="6">
            <v-btn v-if="$perms('system_dict_insert')" color="primary" @click="handleInsert">
              <v-icon start>mdi-plus</v-icon>
              添加
            </v-btn>
          </v-col>
          <v-col cols="12" md="6">
            <v-text-field v-model="queryForm.dictName_LIKE" label="字典名称" placeholder="请输入字典名称" clearable
              variant="outlined" density="compact" append-inner-icon="mdi-magnify" @click:append-inner="queryData"
              @keyup.enter="queryData"></v-text-field>
          </v-col>
        </v-row>

        <!-- 数据表格 -->
        <v-data-table :headers="headers" :items="list" :loading="listLoading" 
          :items-per-page="10" :items-per-page-options="[10, 20, 50, 100]"
          class="elevation-9 rounded-lg" loading-text="正在加载..." no-data-text="暂无数据">
          <!-- 是否内置列 -->
          <template v-slot:item.izLock="{ item }">
            <v-chip :color="item.izLock === '0' ? 'success' : 'info'" size="small" variant="flat">
              {{ $getDictNameByValue('no_yes', item.izLock) }}
            </v-chip>
          </template>

          <!-- 操作列 -->
          <template v-slot:item.actions="{ item }">
            <div class="d-flex gap-2">
              <v-btn v-if="$perms('system_dict_update')" size="small" variant="text" color="primary"
                @click="handleUpdate(item)">
                编辑
              </v-btn>
              <v-btn v-if="$perms('system_dict_delete')" size="small" variant="text" color="error"
                @click="handleDelete(item)">
                删除
              </v-btn>
            </div>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <!-- 编辑对话框 -->
    <DictDetailEdit ref="dictDetailEditRef" @fetchData="fetchData" />
  </v-navigation-drawer>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';
import { getList, doDelete } from '@/api/system/dict/dictDetailManagement';
import { isNull } from '@/utils/validate';
import { getUserInfo } from '@/api/user';
import { useMessage } from '@/composables/useMessage';
import DictDetailEdit from './dictDetailEdit.vue';

const { proxy } = getCurrentInstance();
const { success: showSuccess, error: showError } = useMessage();

// 响应式数据
const dictDetailVisible = ref(false);
const title = ref('');
const userInfo = ref(null);
const izLock = ref('0');
const list = ref([]);
const listLoading = ref(true);
const total = ref(0);

const dictType = ref({
  typeId: '',
  typeCode: ''
});

const queryForm = ref({
  typeId_EQ: '',
  dictName_LIKE: '',
  sortNo_ORDER: 'ASC'
});

// 表格头部配置
const headers = ref([
  {
    title: '字典名称',
    key: 'dictName',
    align: 'start',
    sortable: false
  },
  {
    title: '字典值',
    key: 'dictValue',
    align: 'start',
    sortable: false
  },
  {
    title: '排序',
    key: 'sortNo',
    align: 'center',
    sortable: false,
    width: '100px'
  },
  {
    title: '是否内置',
    key: 'izLock',
    align: 'center',
    sortable: false,
    width: '120px'
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    sortable: false,
    width: '130px'
  }
]);

// 组件引用
const dictDetailEditRef = ref();

/**
 * 显示字典详情
 */
const show = (row) => {
  dictDetailVisible.value = true;
  dictType.value.typeId = row.id;
  dictType.value.typeCode = row.typeCode;
  queryForm.value.typeId_EQ = row.id;
  title.value = row.typeName;
  izLock.value = row.izLock;

  fetchData();
};

/**
 * 关闭抽屉
 */
const close = () => {
  list.value = [];
  title.value = '';
  queryForm.value.typeId_EQ = '';
  queryForm.value.dictName_LIKE = '';
  dictDetailVisible.value = false;
};

/**
 * 添加字典项
 */
const handleInsert = () => {
  // 如果用户信息为空或者不是超级管理员则无法更改内置数据
  if (isNull(userInfo.value) || !userInfo.value.izSuperAdmin) {
    if (izLock.value === '1') {
      showError('内置数据只有超级管理员可以更改');
      return;
    }
  }
  dictDetailEditRef.value?.showInsert(dictType.value);
};

/**
 * 编辑字典项
 */
const handleUpdate = (row) => {
  // 如果用户信息为空或者不是超级管理员则无法更改内置数据
  if (isNull(userInfo.value) || !userInfo.value.izSuperAdmin) {
    if (row.izLock === '1') {
      showError('内置数据只有超级管理员可以更改');
      return;
    }
  }

  if (row.id) {
    dictDetailEditRef.value?.showUpdate(row);
  }
};

/**
 * 删除字典项
 */
const handleDelete = async (row) => {
  // 如果用户信息为空或者不是超级管理员则无法更改内置数据
  if (isNull(userInfo.value) || !userInfo.value.izSuperAdmin) {
    if (row.izLock === '1') {
      showError('内置数据只有超级管理员可以更改');
      return;
    }
  }

  if (row.id) {
    const confirmed = confirm('你确定要删除当前项吗？');
    if (confirmed) {
      try {
        const response = await doDelete({ id: row.id });
        showSuccess(response.msg || '删除成功');
        await fetchData();
      } catch (error) {
        console.error('删除失败:', error);
        showError('删除失败');
      }
    }
  }
};

/**
 * 查询数据
 */
const queryData = () => {
  fetchData();
};

/**
 * 获取数据
 */
const fetchData = async () => {
  listLoading.value = true;

  try {
    // 设置大的pageSize获取全部数据，用于客户端分页
    const params = {
      pageNo: 1,
      pageSize: 1000, // 设置足够大的数量获取全部数据
      typeId_EQ: queryForm.value.typeId_EQ,
      dictName_LIKE: queryForm.value.dictName_LIKE,
      sortNo_ORDER: queryForm.value.sortNo_ORDER
    };
    
    const { data } = await getList(params);
    if (data) {
      list.value = data.rows || [];
      total.value = data.total || 0;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    showError('获取数据失败');
  } finally {
    setTimeout(() => {
      listLoading.value = false;
    }, 300);
  }
};

/**
 * 获取用户信息
 */
const getUser = async () => {
  try {
    const { data } = await getUserInfo();
    userInfo.value = data;
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 初始化用户信息
getUser();

// 暴露方法
defineExpose({
  show
});
</script>

<style scoped>
.dict-detail-drawer {
  z-index: 2000;
}
</style>
